#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2012/02/16

Module that creates a http server in a new thread.
Uses the KThread module.
    Exemple: http://www.velocityreviews.com/forums/t330554-kill-a-thread-in-python.html
    Download: http://code.google.com/p/pystatecharts/source/browse/trunk/KThread.py?spec=svn44&r=44

Based on student 6207 code with some bug fixes.

@author: João Vitor Machado Batista nº 5479
'''

import SimpleHTTPServer
import SocketServer
import webbrowser
from KThread import *
from FilesMaker import *

class HTTPServer (threading.Thread):

    thread = None

    def stop (self):
        '''
            Kills the thread
        '''
        global thread
        thread.kill()
        self.open_Browser()
        pass
    
    def start_server (self):
        '''
            Starts a thread with a function
        '''
        global thread
        thread = KThread(target=self.def_server)
        thread.start()
	self.open_Browser()
        pass

    def def_server (self):
        '''
            Creates a server
        '''
	objFilesMaker = FilesMaker()
        objFilesMaker.htmlIndexFileCreator()
        PORT = 8000
        Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
        server = SocketServer.TCPServer(('', PORT), Handler)        
        #print "HTTP serving at port: " + str(PORT)
        server.serve_forever()
        pass

    def open_Browser(self):
        '''
            Opens the web-browser in the server
        '''
        url = 'http://localhost:8000/'
        webbrowser.open(url)
        pass
